/*
 * Lenovo Group
 * Copyright (c) 2015-2016 All Rights Reserved.
 * Project Name: lmrp-android app
 * Create Time: 16-2-16 下午6:45
 */

package com.lenovo.mso2o.ui.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.core.VehicleInfo;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.route.DrivingRouteLine;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteLine;
import com.baidu.mapapi.search.route.TransitRoutePlanOption;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteLine;
import com.baidu.mapapi.search.route.WalkingRoutePlanOption;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.lenovo.framework.base.InjectableFragment;
import com.lenovo.framework.util.DLog;
import com.lenovo.framework.util.overlayutil.DrivingRouteOverlay;
import com.lenovo.framework.util.overlayutil.TransitRouteOverlay;
import com.lenovo.framework.util.overlayutil.WalkingRouteOverlay;
import com.lenovo.mso2o.R;
import com.lenovo.mso2o.util.Utils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

public class GuideFragment extends InjectableFragment implements OnGetRoutePlanResultListener, OnGetGeoCoderResultListener,
        BDLocationListener {
    //控件绑定
    @Bind(R.id.mapView)
    MapView mMapview;
    //    @Bind(R.id.image_guidNormal)
//    ImageView image_guideNormal;
    @Bind(R.id.image_guideFollow)
    ImageView image_guideFollow;
    @Bind(R.id.relative_guideTab)
    RelativeLayout guideTab;
    @Bind(R.id.tv_guideInfo_scheme)
    TextView tv_guideScheme;
    @Bind(R.id.tv_guideInfo_fee)
    TextView tv_guideFee;
    @Bind(R.id.tv_guideInfo_trafficlight)
    TextView tv_guideLight;
    @Bind(R.id.image_guideInfo)
    ImageView guideInfo;
    @Bind(R.id.radioGroup_guideWays)
    RadioGroup radioGroup;
    @Bind(R.id.radiobtn_busGuide)
    RadioButton busbtn;
    @Bind(R.id.radiobtn_taxiGuide)
    RadioButton taxibtn;
    @Bind(R.id.radiobtn_walkGuide)
    RadioButton walkbtn;
    @Bind(R.id.lin_guideInfo_detail)
    LinearLayout linear_guideDetail;
    @Bind(R.id.text_guideStartpoint)
    TextView tv_startPoint;
    @Bind(R.id.text_processDetail)
    TextView tv_process;
    @Bind(R.id.text_guideEndpoint)
    TextView tv_endPoint;

    @OnClick(R.id.relative_guideTab)
    public void onGuideDetail() {
        if (linear_guideDetail.getVisibility() == View.VISIBLE) {
            linear_guideDetail.startAnimation(downAnim);
            linear_guideDetail.setVisibility(View.GONE);
//            guideInfo.startAnimation(normalRotate);
            guideInfo.setRotation(0f);
        } else {
            linear_guideDetail.startAnimation(upAnim);
            linear_guideDetail.setVisibility(View.VISIBLE);
//            guideInfo.startAnimation(reverseRotate);
            guideInfo.setRotation(180f);
        }
    }

    //升起动画
    private Animation upAnim;
    private Animation downAnim;
    private Animation reverseRotate;
    private Animation normalRotate;
    private String startPoint;
    private String endPoint;


    //全局变量声明
    private RoutePlanSearch mSerch = null;//路线搜索实例
    private GeoCoder mGeocoder = null;//地理编码实例
    private LocationClient locationClient = null;//定位实例
    private LocationClientOption locationClientOption = null;//定位参数
    private BaiduMap mBaidumap = null;//地图实例
    private PlanNode startNode;
    private PlanNode endNode;
    private String cityName;//当前所在城市
    private double startLat;//起点纬度
    private double startLog;//起点经度
    private double endLat;//终点纬度
    private double endLog;//终点经度
    private LatLng startLG;//起点位置
    private LatLng endLG;//终点位置
    private boolean isNormalType = true;//当前默认普通模式地图
    private MyLocationConfiguration.LocationMode mCurrentMode;//地图模式
    private BitmapDescriptor mCurrentMarker;//当前使用标注

    //参数传递所需常量
    public static final String START_LAT = "start_lat";
    public static final String END_LAT = "end_lat";
    public static final String START_LOG = "start_log";
    public static final String END_LOG = "end_log";
    public static final float GUIDEICON_ALPH = 0.6F;
    public static final float GUIDEICON_ABS_ALPH = 1.0F;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        upAnim = AnimationUtils.loadAnimation(getContext(), R.anim.push_bottom_in);
        downAnim = AnimationUtils.loadAnimation(getContext(), R.anim.push_bottom_out);
        reverseRotate = AnimationUtils.loadAnimation(getContext(), R.anim.reverserotate_anim);
        normalRotate = AnimationUtils.loadAnimation(getContext(), R.anim.normalrotate_anim);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        initMapView();
        return  view;
    }

    @Override
    public int provideContentRes() {
        return R.layout.activity_guide;
    }

    /**
     * 初始化地图视图
     */
    public void initMapView() {
        mSerch = RoutePlanSearch.newInstance();
        mGeocoder = GeoCoder.newInstance();
        mBaidumap = mMapview.getMap();
        mBaidumap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        mBaidumap.setMyLocationEnabled(true);
        //定位
        locationClient = new LocationClient(getContext());
        locationClientOption = new LocationClientOption();
        locationClientOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        locationClientOption.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span = 10 * 1000;
        locationClientOption.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        locationClientOption.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        locationClientOption.setOpenGps(true);//可选，默认false,设置是否使用gps
        locationClientOption.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        locationClientOption.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        locationClientOption.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        locationClientOption.setIgnoreKillProcess(false);//可选，默认false，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认杀死
        locationClientOption.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        locationClientOption.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        locationClient.setLocOption(locationClientOption);
        locationClient.registerLocationListener(this);


        //地图模式
        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
        mCurrentMarker = BitmapDescriptorFactory.fromResource(R.drawable.icon_mylocation);
        mBaidumap
                .setMyLocationConfigeration(new MyLocationConfiguration(
                        mCurrentMode, true, mCurrentMarker));


        //设置监听
        mSerch.setOnGetRoutePlanResultListener(this);
        mGeocoder.setOnGetGeoCodeResultListener(this);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                mBaidumap.clear();
                if (endPoint.isEmpty() || endPoint == null)
                    mGeocoder.reverseGeoCode(new ReverseGeoCodeOption().location(endLG));
                locationClient.registerLocationListener(GuideFragment.this);
                switch (checkedId) {//导航方式
                    case R.id.radiobtn_busGuide://公交
                        mSerch.transitSearch(new TransitRoutePlanOption().from(startNode).city(cityName).to(endNode));
                        busbtn.setAlpha(GUIDEICON_ABS_ALPH);
                        taxibtn.setAlpha(GUIDEICON_ALPH);
                        walkbtn.setAlpha(GUIDEICON_ALPH);


                        break;

                    case R.id.radiobtn_taxiGuide://出租
                        mSerch.drivingSearch(new DrivingRoutePlanOption().from(startNode).to(endNode));
                        busbtn.setAlpha(GUIDEICON_ALPH);
                        taxibtn.setAlpha(GUIDEICON_ABS_ALPH);
                        walkbtn.setAlpha(GUIDEICON_ALPH);
                        break;

                    case R.id.radiobtn_walkGuide://步行
                        mSerch.walkingSearch(new WalkingRoutePlanOption().from(startNode).to(endNode));
                        busbtn.setAlpha(GUIDEICON_ALPH);
                        taxibtn.setAlpha(GUIDEICON_ALPH);
                        walkbtn.setAlpha(GUIDEICON_ABS_ALPH);
                        break;
                }
            }
        });


        //获取起终点坐标值
        Bundle bundle = getArguments();
        //真正获取数据
        if (bundle == null) {
            Toast.makeText(getContext(), "数据获取错误", Toast.LENGTH_LONG).show();
            return;
        }
        endLat = bundle.getDouble(END_LAT, 0d);
        endLog = bundle.getDouble(END_LOG, 0d);
        endLG = new LatLng(endLat, endLog);
        endNode = PlanNode.withLocation(endLG);
        locationClient.start();//发起定位
        mGeocoder.reverseGeoCode(new ReverseGeoCodeOption().location(endLG));
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapview.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapview.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        locationClient.unRegisterLocationListener(this);
        mGeocoder.destroy();
        mSerch.destroy();
        mMapview.onDestroy();
        BMapManager.destroy();
    }

    @Override
    protected void onFragmentInVisible(Bundle savedInstanceState) {

    }

    @Override
    protected void onFragmentVisible(Bundle savedInstanceState) {

    }

    //返回点击事件
    @OnClick(R.id.actionbar_left_layout)//
    public void backClick(View view) {
        getActivity().finish();
    }


    /**
     * 跟随模式普通模式切换操作
     */
    public void followClick(View view) {
        if (mCurrentMode.equals(MyLocationConfiguration.LocationMode.NORMAL)) {
            image_guideFollow.setImageResource(R.drawable.icon_guidenormal);
            mCurrentMode = MyLocationConfiguration.LocationMode.FOLLOWING;
            mBaidumap
                    .setMyLocationConfigeration(new MyLocationConfiguration(
                            mCurrentMode, true, mCurrentMarker));

        } else if (mCurrentMode.equals(MyLocationConfiguration.LocationMode.FOLLOWING)) {
            image_guideFollow.setImageResource(R.drawable.icon_guidefollow);
            mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
            mBaidumap
                    .setMyLocationConfigeration(new MyLocationConfiguration(
                            mCurrentMode, true, mCurrentMarker));

        }


    }

    @Override
    public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {
        guideTab.setVisibility(View.GONE);
        if (walkingRouteResult == null || walkingRouteResult.error != SearchResult.ERRORNO.NO_ERROR) {
            String tip = null;
            if (walkingRouteResult != null) {
                SearchResult.ERRORNO errorno = walkingRouteResult.error;
                if (errorno == SearchResult.ERRORNO.ST_EN_TOO_NEAR) {
                    tip = getString(R.string.too_near);
                }
            }
            Toast.makeText(getContext(), tip == null ? "抱歉，未找到结果" : tip, Toast.LENGTH_SHORT).show();
            locationClient.unRegisterLocationListener(this);
            return;
        }
        if (walkingRouteResult.error == SearchResult.ERRORNO.NO_ERROR) {
            guideTab.setVisibility(View.VISIBLE);
            guideTab.requestFocus();
            WalkingRouteOverlay overlay = new WalkingRouteOverlay(mBaidumap);
            mBaidumap.setOnMarkerClickListener(overlay);
            overlay.setData(walkingRouteResult.getRouteLines().get(0));
            overlay.addToMap();
            overlay.zoomToSpan();
            ArrayList<WalkingRouteLine> walklines = (ArrayList<WalkingRouteLine>) walkingRouteResult.getRouteLines();
            WalkingRouteLine line = walklines.get(0);
            ArrayList<WalkingRouteLine.WalkingStep> steps = (ArrayList<WalkingRouteLine.WalkingStep>) line.getAllStep();
            StringBuilder titleBuilder = new StringBuilder("");
            int distance = 0;
            int duration = 0;
            String end = "";
            for (WalkingRouteLine.WalkingStep step : steps) {
                titleBuilder.append(step.getInstructions() + ">");
                distance += step.getDistance();
                duration += step.getDuration();
                end = step.getExitInstructions();
            }
//            tv_guideScheme.setText(end);
            tv_process.setText(titleBuilder.toString());
            tv_guideFee.setText("距离：" + distance + "米");
            tv_guideLight.setText("时间：" + duration / 60 + "分钟");
        }
    }

    @Override
    public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {
        guideTab.setVisibility(View.GONE);
        if (transitRouteResult == null || transitRouteResult.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(getContext(), "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
            locationClient.unRegisterLocationListener(this);
        }
        if (transitRouteResult.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
            //起终点或途经点地址有岐义，通过以下接口获取建议查询信息
            //result.getSuggestAddrInfo()
            return;
        }
        if (transitRouteResult.error == SearchResult.ERRORNO.NO_ERROR) {
            guideTab.setVisibility(View.VISIBLE);
            guideTab.requestFocus();
            TransitRouteOverlay overlay = new TransitRouteOverlay(mBaidumap);
            mBaidumap.setOnMarkerClickListener(overlay);
            overlay.setData(transitRouteResult.getRouteLines().get(0));
            overlay.addToMap();
            overlay.zoomToSpan();
            guideTab.setVisibility(View.VISIBLE);
            StringBuilder titleBuilder = new StringBuilder("");
            int distance = 0;
            float duration = 0;
            List<TransitRouteLine> lines = transitRouteResult.getRouteLines();
            TransitRouteLine line = lines.get(0);
            ArrayList<TransitRouteLine.TransitStep> steps = (ArrayList<TransitRouteLine.TransitStep>) line.getAllStep();
            for (TransitRouteLine.TransitStep step : steps) {
                VehicleInfo info = step.getVehicleInfo();
                if (step.getStepType() == TransitRouteLine.TransitStep.TransitRouteStepType.BUSLINE || step.getStepType() == TransitRouteLine.TransitStep.TransitRouteStepType.SUBWAY) {
                    titleBuilder.append(info.getTitle() + "/");
                }
                distance += step.getDistance();
                duration += step.getDuration();
            }
            tv_process.setText(titleBuilder);
            tv_guideFee.setText("距离:" + distance + "米");
            tv_guideLight.setText("时间:" + duration / 60 + "分钟");
        }
    }

    @Override
    public void onGetDrivingRouteResult(DrivingRouteResult drivingRouteResult) {
        guideTab.setVisibility(View.GONE);
        if (drivingRouteResult == null || drivingRouteResult.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(getContext(), "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
            locationClient.unRegisterLocationListener(this);
        }
        if (drivingRouteResult.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
            //起终点或途经点地址有岐义，通过以下接口获取建议查询信息
            //result.getSuggestAddrInfo()
            return;
        }
        if (drivingRouteResult.error == SearchResult.ERRORNO.NO_ERROR) {
            guideTab.setVisibility(View.VISIBLE);
            guideTab.requestFocus();
            DrivingRouteOverlay overlay = new DrivingRouteOverlay(mBaidumap);
            mBaidumap.setOnMarkerClickListener(overlay);
            overlay.setData(drivingRouteResult.getRouteLines().get(0));
            overlay.addToMap();
            overlay.zoomToSpan();
            int distance = 0;
            int duration = 0;
            StringBuilder trafficlights = new StringBuilder("");
            DrivingRouteLine line = drivingRouteResult.getRouteLines().get(0);
            ArrayList<DrivingRouteLine.DrivingStep> steps = (ArrayList<DrivingRouteLine.DrivingStep>) line.getAllStep();
            for (DrivingRouteLine.DrivingStep step : steps) {
                distance += step.getDistance();
                trafficlights.append(step.getInstructions() + ">");
            }

            tv_process.setText(trafficlights);
            tv_guideFee.setText("距离:" + distance + "米");
            tv_guideLight.setText("时间：" + line.getDuration() / 60 + "分钟");
        }
    }

    @Override
    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
        if (geoCodeResult == null || geoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
            //没有检索到结果
            endPoint = "";
            Toast.makeText(getContext(), "没有找到目的地信息", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
        if (reverseGeoCodeResult == null || reverseGeoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
            //没有找到检索结果
            Toast.makeText(getContext(), "没有找到检索结果", Toast.LENGTH_LONG).show();
            return;
        }
        //根据地理反编码获取
        endPoint = reverseGeoCodeResult.getAddress();
        tv_endPoint.setText(endPoint);
        tv_guideScheme.setText(endPoint);
//        endLG = reverseGeoCodeResult.getLocation();
//        endNode = PlanNode.withLocation(endLG);
//
//
//        if (startNode != null)
//            endPoint = endNode
//            mSerch.transitSearch(new TransitRoutePlanOption().from(startNode).city(cityName).to(endNode));
    }

    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        //设置起始信息
        startPoint = bdLocation.getAddrStr();
        tv_startPoint.setText(startPoint);
        MyLocationData locData = new MyLocationData.Builder()
                .accuracy(bdLocation.getRadius())
                        // 此处设置开发者获取到的方向信息，顺时针0-360
                .direction(100).latitude(bdLocation.getLatitude())
                .longitude(bdLocation.getLongitude()).build();
// 设置定位数据
        mBaidumap.setMyLocationData(locData);
//获取所在城市
        cityName = bdLocation.getCity();


        //位置变化后，实时发起路线规划
        startNode = PlanNode.withLocation(new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude()));
        if (endNode != null) {
            if (mSerch == null)
                return;
            try {
                if (busbtn.isChecked()) {
                    mSerch.transitSearch(new TransitRoutePlanOption().from(startNode).city(cityName).to(endNode));
                } else if (taxibtn.isChecked()) {
                    mSerch.drivingSearch(new DrivingRoutePlanOption().from(startNode).to(endNode));
                } else if (walkbtn.isChecked()) {
                    mSerch.walkingSearch(new WalkingRoutePlanOption().from(startNode).to(endNode));
                }
            } catch (Exception e) {
                DLog.p(e);
            }
        } else {
            Toast.makeText(getContext(), "未知地点，无法导航", Toast.LENGTH_LONG).show();
        }
    }

}
